#include "stdafx.h"
#include "LogFileWriter.h"

#ifndef LINUX_NAS
CRITICAL_SECTION g_stu_log_file_writer_lock;
#else
pthread_mutex_t g_stu_log_file_writer_lock;
#endif

static int lockCount = 0;

CLogFileWriter::CLogFileWriter(void)
{
}

CLogFileWriter::~CLogFileWriter(void)
{
}

#define TRUNC_SIZE (10*1024*1024)

void CLogFileWriter::Lock()
{
	if(lockCount == 0)
		InitCritical(g_stu_log_file_writer_lock);
	EnterCritical(g_stu_log_file_writer_lock);
	lockCount = 1;
}

void CLogFileWriter::UnLock()
{
	LeaveCritical(g_stu_log_file_writer_lock);
}

void CLogFileWriter::Print(int level, char* fileName, int lineNumber, char* functionName, char* log, ...)
{
	if (level == _DEBUG_)
		return;

	char* szBuff = new char[2048];
	memset(szBuff, 0, 2048);
	long file_size;
	va_list vl;

	va_start(vl, log);
	vsprintf(szBuff, log, vl);
	va_end(vl);

	SYSTEMTIME sysTime;
	GetLocalTime(&sysTime);
	char log_fileName[256] = {0};
#ifndef LINUX_NAS
	sprintf(log_fileName, "%s\\caymay_%04d%02d.log", g_WorkDir, sysTime.wYear, sysTime.wMonth);
#else
	sprintf(log_fileName, "/raid0/data/usbhdd/usb/caymay_%04d%02d.log", sysTime.wYear, sysTime.wMonth);
#endif
	Lock();

	FILE* fp = fopen(log_fileName, "a");
	if (fp == NULL)
	{
		UnLock();
		delete[] szBuff;
		return;
	}

	char* pauseTime = new char[2048];
	sprintf(pauseTime, "%04d-%02d-%02d %02d-%02d-%02d:%03d - %s:%d - %s - %s \r\n", sysTime.wYear, sysTime.wMonth, sysTime.wDay, sysTime.wHour, sysTime.wMinute, sysTime.wSecond, sysTime.wMilliseconds
		, fileName, lineNumber, functionName, szBuff);

	fwrite(pauseTime, strlen(pauseTime), 1, fp);
	fseek(fp, 0, SEEK_END);	 
	file_size = ftell(fp);
	fclose(fp);

	delete[] pauseTime;
	delete[] szBuff;

	if(file_size > TRUNC_SIZE)
	{
		fp = fopen(log_fileName, "w");
		if (fp != NULL)
			fclose(fp);
	}

	UnLock();
}
